package artem;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIOServer extends Thread {
	private ServerSocketChannel serverChannel;

	public static void main(String[] args) {
		NIOServer server = new NIOServer();
		server.start();
	}

	public void run() {
		try {
			serverChannel = ServerSocketChannel.open();
			serverChannel.bind(new InetSocketAddress(7778));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try (SocketChannel socket = serverChannel.accept();
				FileChannel file = FileChannel.open(
						Paths.get("data\\dst4.bin"), StandardOpenOption.CREATE,
						StandardOpenOption.TRUNCATE_EXISTING,
						StandardOpenOption.WRITE)) {

			ByteBuffer bb = ByteBuffer.allocate(100000);
			while (socket.read(bb) != -1) {
				bb.flip();
				file.write(bb);
				bb.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
